package room_event

import (
	"encoding/json"
	"fmt"
	"github.com/godruoyi/go-snowflake"
	"github.com/spf13/cast"
	"longmen/server/config/global"
	"longmen/server/internal/rpc/tencentim/chat"
	"longmen/server/internal/rpc/tencentim/imsdk"
	messages2 "longmen/server/internal/rpc/tencentim/messages"
	"longmen/server/internal/rpc/tencentim/messages/mgr_message"
	mgr_chat2 "longmen/server/internal/rpc/tencentim/mgr_chat"
	"longmen/server/internal/rpc/tencentim/utils"
	"longmen/server/pkg/common/lib/bytesconv"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/redis/cache"
	pb "longmen/server/pkg/protobuf"
	"strconv"
	"time"
)

// handlingMgrMessage 处理房管私聊回调信息
func handlingMgrMessage(user *chat.ClientUser, data []byte) (*pb.CallbackResp, error) {
	// 判断是否发言频繁
	if !global.GetRds().SetNX(fmt.Sprintf("user_say:%d", user.UserId), 1, time.Second*1).Val() {
		return utils.C2CRejectMessage("发言频繁"), nil
	}

	// 解析自定义发言内容
	say := mgr_message.SayMessage{}
	err := json.Unmarshal(data, &say)
	if err != nil {
		return utils.C2CRejectMessage("发言内容错误"), nil
	}

	//判断发送者身份, 并且插入新的聊天列表记录
	isMgr, mgrChat, err := mgr_chat2.CheckUserMgr(user.UserId, say.GroupId)
	if err != nil {
		global.Log.Error(err)
		return utils.C2CRejectMessage(err.Error()), nil
	}

	// 房管未回复仅接收10条信息
	if !isMgr {
		num := cache.GetMgrChatRepeatNum(user.UserId)
		if num >= 10 {
			return utils.C2CRejectMessage("请耐心等待房管回复"), nil
		}
		defer cache.IncrMgrChatRepeatNum(user.UserId)
	} else {
		// 房管回复清除发送条数计数
		cache.ResetMgrChatRepeatNum(say.GroupId)
	}

	// 判断文本图片类型
	if len(say.Content) <= 0 && len(say.ImageUrl) <= 0 {
		return utils.C2CRejectMessage("发言内容不能为空"), nil
	}

	// 解密
	var content string
	respContent := say.Content
	if len(say.Content) > 0 {
		content, err = cache.AesDescrypt(say.Content)
		if err != nil {
			global.Log.Error(err)
			return utils.C2CRejectMessage("发言内容错误"), nil
		}
		say.Content = content
	}

	// 计算身份
	role := 0
	if isMgr {
		role = 1
	}

	//判断消息类型
	textType := mgr_chat2.MgrHistoryCommonType
	if len(say.ImageUrl) > 0 {
		textType = mgr_chat2.MgrHistoryImageType
	}

	// 聊天历史写入到ES
	h := mgr_chat2.History{
		Id:          cast.ToString(snowflake.ID()),
		ChatId:      mgr_chat2.GetChatId(mgrChat),
		SenderUid:   user.UserId,
		ReceiveUid:  say.GroupId,
		Avatar:      user.Avatar,
		Nickname:    user.ClientName,
		Content:     say.Content,
		SendTime:    time.Now().Unix(),
		Role:        role,
		TextType:    textType,
		ImageUrl:    say.ImageUrl,
		ImageWidth:  say.ImageWidth,
		ImageHeight: say.ImageHeight,
	}
	writeOk := h.WriteToEs()
	if !writeOk {
		return utils.C2CRejectMessage("发送频繁，请休息一下"), nil
	}

	// 清除自身未读计数, 对方计数+1
	defer func() {
		cache.ResetMgrChatUserReadNum(user.UserId, say.GroupId)
		cache.IncrMgrChatUserReadNum(say.GroupId, user.UserId)
	}()

	// 允许发言
	typ := messages2.MgrMessageReplyType
	resp, _ := json.Marshal(mgr_message.ReplyMessage{
		IncomingMessage: messages2.IncomingMessage{
			Type:    &typ,
			GroupId: user.UserId,
		},
		Id:          h.Id,
		ChatId:      h.ChatId,
		Content:     respContent,
		SenderUid:   h.SenderUid,
		ReceiveUid:  h.ReceiveUid,
		Avatar:      user.Avatar,
		Nickname:    user.ClientName,
		SendTime:    time.Now().Unix(),
		Role:        h.Role,
		TextType:    h.TextType,
		ImageUrl:    h.ImageUrl,
		ImageWidth:  h.ImageWidth,
		ImageHeight: h.ImageHeight,
	})
	retryTimes := 3
	for i := 0; i < retryTimes; i++ {
		err = imsdk.GetSdk().SendUser(strconv.Itoa(say.GroupId), bytesconv.BytesToString(resp))
		if err != nil {
			global.Log.Error(err)
			continue
		}
		break
	}
	return utils.CallbackOkResp(nil), nil
}

// handlingMgrHistory 处理房管私聊历史信息获取
func handlingMgrHistory(user *chat.ClientUser, data []byte) (*pb.CallbackResp, error) {
	his := mgr_message.HistoryMessage{}
	err := json.Unmarshal(data, &his)
	if err != nil {
		return nil, err
	}

	//判断发送者身份, 并且插入新的聊天列表记录
	_, mgrChat, err := mgr_chat2.CheckUserMgr(user.UserId, his.GroupId)
	if err != nil {
		return nil, err
	}

	//查询删除记录
	mDel, _ := db_main.GetMgrChatDelete(map[string]interface{}{
		"user_id":      user.UserId,
		"chat_user_id": his.GroupId,
	})
	delStamp := int64(0)
	if mDel.Id > 0 {
		delStamp = mDel.CreateStamp
	}

	defer cache.ResetMgrChatUserReadNum(user.UserId, his.GroupId)
	history, total := mgr_chat2.GetHistory(mgr_chat2.GetChatId(mgrChat), his.Page, his.Limit, delStamp)
	resp := mgr_message.HistoryResponse{
		SentMessageStruct: messages2.SentMessageStruct{Type: messages2.MgrHistoryReplyType},
		Data:              history,
		Total:             total,
	}
	return utils.CallbackOkAndExt(resp, ""), nil
}
